// pages/control/index.js
import * as echarts from '../ec-canvas/echarts';
const app = getApp();
function pieSet(chart, data) {
  var option = {
    color:["#6699FF","#EBEEF5"],
    title: {
      show: true,
      text: data + '%',
      x: 'center',
      y: 'center',
      textStyle: {
        fontSize: '15',
        color: 'black',
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: "{d}%",
      show: false
    },
    legend: {
      orient: 'vertical',
      x: 'left',
      show: false
    },
    series:
    {
      name: '',
      type: 'pie',
      radius: ['65%', '85%'],
      avoidLabelOverlap: true,
      hoverAnimation: false,
      label: {
        normal: {
          show: false,
          position: 'center'
        },
        emphasis: {
          show: false
        }
      },
      labelLine: {
        normal: {
          show: false
        }
      },
      data: [
        { value: data, name: '' },
        { value: 100 - data, name: '' }
      ]
    }

  }
  chart.setOption(option);
  return chart;
}
function lineSet(chart, dataX, dataY) {
  var option = {
    color: ["#ED6D14"],
    grid: {
      bottom: "50px",
      right: "20px",
      left:"70px",
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: dataX,
    },
    yAxis: {
      type: "value",
      axisLabel: {
        formatter: "{value}%",
      },
    },
    tooltip: {
      trigger: "axis",
    },
    series: [
      {
        data: dataY,
        type: "line",
        
        areaStyle: {},
      },
    ],
  }
  chart.setOption(option);
  return chart;
}
function cycleSet(chart, opentime, closetime) {
  var option = {
    tooltip: {
      trigger: 'item',
      formatter: "{a} <br/>{b} : {c}H ({d}%)",
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      show: false
    },

    series: [
      {
        name: {},
        type: 'pie',
        radius: '70%',
        data: [
          {
            value: opentime,
            name: "开机时间",
            itemStyle: { normal: { color: "#70b4eb" } },
          },
          {
            value: closetime,
            name: "关机时间",
            itemStyle: { normal: { color: "#7dc8a8" } },
          },
        ],
        label: {
          alignTo: "edge",
          formatter: "{b}:{d}%",
          show: false
        },
        labelLine: {
          show: false
        },
      }
    ]
  }
  chart.setOption(option);
  return chart;
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    array3: [],
    index: 0,
    ec: {
      lazyLoad: true
    },
    enviorList: [],
    line: {
      lazyLoad: false
    },
    cashList: [],
    qaData: [],
    predictData: [],
    H_EQP: "0",
    H_TMT: "0",
    T_EQP: "0",
    T_TMT: "0",
    mvctData: "0",
    TxData: "0",
    openTime: "",
    closeTime: "",
    code: "",
    tempArr:[{ruleName:"111",paramValue:"2222",unit:"333",content:"77",threshold:"888"}]
  },
  //获取选择的分类
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })

  },
  bindPicker3Change: function (e) {
    console.log(e)
    this.setData({
      value3: e.detail.value,
      code: this.data.array3[e.detail.value]
    })
    this._getOpenTime()

    this._getRing()
    this._getPreLog()
    this._getChartData()
    this._getWorkLoad()
    console.log(this.data.code)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //this.initPieChart(90)
    this._getSearch()
    // this._getOpenTime()
    // this.initCycleChart()
    // this._getRing()
    // this._getPreLog()
    // this._getChartData()
    // this. _getWorkLoad()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.initCycleChart()
    this._getRing()
    this._getPreLog()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      let tempArr = this.getTabBar().data.itemMenu
      let index = tempArr.findIndex((item) => {
        if (item.power == '4znyj') {
          return true
        }
      })
      console.log(index, '索引')
      this.getTabBar().setData({
        selected: index
      })
    }
  },
  // 获取下拉框设备列表
  _getSearch() {
    let that = this;
    that
      .axios
      .custom("AllInstalledProducts", "serialOrLotNumbers", {
        id: that.Store.getItem("userid"),
      })
      .then((res) => {
        console.log(res, "1.获取设备编号");
        if (res.data != undefined&&res.data.length>0) {
          this.setData({
            array3: res.data,
            value3: 0
          })
          this.setData({
            code: res.data[0]
          })
          this._getOpenTime()
          this.initCycleChart()
          this._getRing()
          this._getPreLog()
          this._getChartData()
          this._getWorkLoad()
        }

      })
  },
  // 预警的接口 获取健康成功率
  _getRing() {
    let that = this;
    let equipId = this.data.code;
    this.axios.custom("Warning", "getWarning", equipId)
      .then((res) => {
        if (res.code == '200') {
          let tempDataX = [];
          let tempDataY = [];
          res.data.dailyErrorLog.forEach((item) => {
            tempDataX.push(item.time);
            tempDataY.push(item.rate);
          });
          if (res.data.load) {
            that.setData({
              cashList: res.data.load
            })
          }
          // QA预警
          if (res.data.todayWarning) {
            that.setData({
              qaData: res.data.todayWarning
            })
          }
          if (res.env) {
            that.setData({
              enviorList: res.data.env
            })
          }
          that.initPieChart(res.data.healthRate)
          that.initLineChart(tempDataX, tempDataY)
          console.log(res, "0,全部数据");
        }

      });
  },
  _getChartData() {
    let that = this;
    let params = {};
    //params.equipId = this.equipId;
    params.serialOrLotNumber = this.data.code;
    //params.equipId = "10001";
    that.axios.custom("EquipParamValue", "summary", params)
      .then((res) => {
        if (res.data.H_EQP.value) {
          this.setData({
            H_EQP: res.data.H_EQP.value
          })
        }
        if (res.data.H_TMT.value) {
          this.setData({
            H_TMT: res.data.H_TMT.value
          })
        }
        if (res.data.T_EQP.value) {
          this.setData({
            T_EQP: res.data.T_EQP.value
          })

        }
        if (res.data.T_TMT.value) {
          this.setData({
            T_TMT: res.data.T_TMT.value
          })

        }
        //  that.checkH_EQP(H_EQP, time);
        // that.checkH_TMT(H_TMT, time);
        //  that.checkT_EQP(T_EQP, time);
        // that.checkT_TMT(T_TMT, time);
        console.log(res, "查看数据");
      });
  },
  // 获取工作负荷统计
  _getWorkLoad() {
    let self = this;
    let params = {};
    params.serialOrLotNumber = this.data.code; // 替换
    params.locationName = "";
    this.axios.custom("AssetLoadCalendarInformation", "beamOnHourSum", params)
      .then((res) => {
        console.log(res, '工作负荷统计');
        this.setData({
          mvctData: res.data.imageOn,
          TxData: res.data.treatmentOn
        })
      });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  // 初始化饼图
  initPieChart(rate) {
    this.RingDom = this.selectComponent('#mychart-dom-pie');
    this.RingDom.init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      canvas.setChart(chart);
      pieSet(chart, rate)
      this.chart = chart;
      return chart;
    });
  },
  // 初始化折线图
  initLineChart(dataX, dataY) {
    this.LineDom = this.selectComponent('#mychart-dom-line');
    this.LineDom.init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, {
        width: 300,
        height: 200,
        devicePixelRatio: dpr // new
      });
      canvas.setChart(chart);
      lineSet(chart, dataX, dataY)
      this.chart = chart;
      return chart;
    });
  },
  // 初始化折线图
  initCycleChart() {
    this.LineDom = this.selectComponent('#mychart-cycle');
    this.LineDom.init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      canvas.setChart(chart);
      cycleSet(chart, this.data.openTime, this.data.closeTime)
      this.chart = chart;
      return chart;
    });
  },
  _getPreLog() {
    let that = this;
    let obj = {};
    obj.code = this.data.code;
    that
      .axios
      .custom("HealthControlRecord", "getPmWarningInformation", obj)
      .then((res) => {
        console.log(res, "F10.保养计划");
        that.setData({
          predictData: res.data
        })

      })
      .catch((e) => {
        console.log(e, "报错");
      });
  },
  // 获取开关机时间
  _getOpenTime() {
    let self = this;
    let params = {};
    params.code = this.data.code;
    params.type = "5";
    self.axios
      .query("AssetLoadCalendarInformation", {}, params)
      .then((res) => {
        //console.log(res, "5.请求", self.openTimeData, "图表的数据");
        this.setData({
          openTime: res.data.rows[0].startupUtilizationViewModel.value1,
          closeTime: res.data.rows[0].startupUtilizationViewModel.value2
        })
        self.initCycleChart()
      });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})